//
//  WBUserAccount.swift
//  Weibo
//
//  Created by 伏文东 on 2018/1/26.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit

private let  accountFile: NSString = "useraccount.json"
/// 用户账户信息
class WBUserAccount: NSObject {
    @objc var access_token: String? //= "2.00ALY3sCWfAa2C35da1177020OI_4y"
    
    @objc var uid: String?
    @objc var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    // 开发者5 年
    // 使用者3 天， 会从第一次登陆 递减
    @objc var expiresDate : Date?
    
    @objc var screen_name: String?
    @objc var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        // 从磁盘加载保存的文件
        // 1>, 加载磁盘二进制文件数据
        guard let path = accountFile.cz_appendDocumentDir(), let data = NSData(contentsOfFile: path), let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any] else { return }
        
        yy_modelSet(with: dict ?? [:])
        
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            access_token = nil
            uid = nil
            try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    /**
     1.偏好设置
     2.沙盒 - 归档 / plist / ·json·
     3.数据库（FMDB/CoreData）
     4.钥匙串访问
     */
    func saveAccount() {
        //1 .模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),let filePath = accountFile.cz_appendDocumentDir() else {
            return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户数据保存成功\(filePath)")
    }
}


































